package com.okaixz.manager.app.service.impl;

import com.alibaba.fastjson2.JSON;
import com.okaixz.client.model.dto.AiRequestParamDto;
import com.okaixz.client.model.dto.AppDto;
import com.okaixz.client.model.dto.AssistantRequest;
import com.okaixz.client.model.dto.WriteResultDto;
import com.okaixz.common.client.exception.BusinessException;
import com.okaixz.common.client.exception.CommonErrorCode;
import com.okaixz.common.client.utils.HttpClientUtil;
import com.okaixz.common.client.utils.MyPageUtil;
import com.okaixz.common.core.page.TableDataInfo;
import com.okaixz.manager.app.domain.AiResult;
import com.okaixz.manager.app.domain.App;
import com.okaixz.client.model.dto.AssistantResult;
import com.okaixz.manager.app.mapper.AppMapper;
import com.okaixz.manager.app.service.IAppService;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 讯飞智能体Service业务层处理
 *
 * @author ruoyi
 * @date 2024-08-20
 */
@Service
@Slf4j
public class AppServiceImpl implements IAppService {
    private String url = "https://spark-api-open.xf-yun.com/v1/chat/completions";

    @Autowired
    private AppMapper appMapper;

    /**
     * 查询讯飞智能体
     *
     * @param id 讯飞智能体主键
     * @return 讯飞智能体
     */
    @Override
    public App selectAppById(Long id) {
        return appMapper.selectAppById(id);
    }

    /**
     * 查询讯飞智能体列表
     *
     * @param app 讯飞智能体
     * @return 讯飞智能体
     */
    @Override
    public List<App> selectAppList(App app) {
        return appMapper.selectAppList(app);
    }

    /**
     * 新增讯飞智能体
     *
     * @param app 讯飞智能体
     * @return 结果
     */
    @Override
    public int insertApp(App app) {
        return appMapper.insertApp(app);
    }

    /**
     * 修改讯飞智能体
     *
     * @param app 讯飞智能体
     * @return 结果
     */
    @Override
    @Transactional
    public int updateApp(App app) {
        return appMapper.updateApp(app);
    }

    /**
     * 批量删除讯飞智能体
     *
     * @param ids 需要删除的讯飞智能体主键
     * @return 结果
     */
    @Override
    public int deleteAppByIds(Long[] ids) {
        return appMapper.deleteAppByIds(ids);
    }

    /**
     * 删除讯飞智能体信息
     *
     * @param id 讯飞智能体主键
     * @return 结果
     */
    @Override
    public int deleteAppById(Long id) {
        return appMapper.deleteAppById(id);
    }

    @Override
    public TableDataInfo clientSelectAppList(App app) {
        List<App> apps = appMapper.selectAppList(app);
        TableDataInfo table = MyPageUtil.getDataTable(apps);
        if (apps == null) {
            return table;
        }
        List<AppDto> appDtoList = apps.stream()
                .map(item -> {
                    AppDto appDto = new AppDto();
                    BeanUtils.copyProperties(item, appDto);
                    return appDto;
                })
                .collect(Collectors.toList());

        table.setRows(appDtoList);
        return table;
    }

    @Override
    public TableDataInfo clientSelectHotAppList(App app) {
        List<App> apps = appMapper.selectHotAppList(app);
        TableDataInfo table = MyPageUtil.getDataTable(apps);
        if (apps == null) {
            return table;
        }
        List<AppDto> appDtoList = apps.stream()
                .map(item -> {
                    AppDto appDto = new AppDto();
                    BeanUtils.copyProperties(item, appDto);
                    return appDto;
                })
                .collect(Collectors.toList());

        table.setRows(appDtoList);
        return table;
    }


    @Override
    public WriteResultDto write(Long appId, String input) {
        App app = appMapper.selectAppById(appId);
        if (app == null) {
            throw new BusinessException(CommonErrorCode.APP_NOT_EXIST);
        }
        app.setUseCount(app.getUseCount() + 1);
        appMapper.updateApp(app);

        String requireMsg = app.getRequireMsg();
        AiRequestParamDto aiRequestParamDto = new AiRequestParamDto();
        aiRequestParamDto.setModel("general");

        AiRequestParamDto.Messages messages = new AiRequestParamDto.Messages();
        messages.setRole("user");
        messages.setContent(requireMsg + input);
        List<AiRequestParamDto.Messages> list = new ArrayList<>();
        list.add(messages);
        aiRequestParamDto.setMessages(list);

        String jsonString = JSON.toJSONString(aiRequestParamDto);
        log.info("json=" + jsonString);
        WriteResultDto writeResultDto = null;
        try {
            String result = HttpClientUtil.doPostJson(url, jsonString);
            AiResult aiResult = JSON.parseObject(result, AiResult.class);

            AiResult.ChoicesDTO choicesDTO = aiResult.getChoices().get(0);
            AiResult.ChoicesDTO.MessageDTO message = choicesDTO.getMessage();

            writeResultDto = new WriteResultDto();
            writeResultDto.setContent(message.getContent());

            //            URI uri = new URI("ws://spark-openapi.cn-huabei-1.xf-yun.com/v1/assistants/adfacmf1zmit_v1");
            //            StringBuilder sb=new StringBuilder();
            //            Thread thread = Thread.currentThread();
            //            MyWebSocketClient client=new MyWebSocketClient(uri,sb,thread);
            //            client.connect();
            //
            //            synchronized (thread) {
            //                try {
            //                    thread.wait();
            //                } catch (Exception e) {
            //                    e.printStackTrace();
            //                }
            //            }
            //            writeResultDto = new WriteResultDto();
            //            writeResultDto.setContent(sb.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }


        return writeResultDto;
    }

    public static class MyWebSocketClient extends WebSocketClient {
        private StringBuilder sb;
        private Thread thread;

        public MyWebSocketClient(URI serverUri, StringBuilder stringBuilder, Thread thread) {
            super(serverUri);
            this.sb = stringBuilder;
            this.thread = thread;
        }

        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            System.out.println("新连接已打开");

            AssistantRequest assistantRequest = new AssistantRequest("72b7aaf5", "uid", "写一篇岳阳楼游记");
            String jsonStr = JSON.toJSONString(assistantRequest);
            System.out.println("request:" + jsonStr);
            try {
                send(jsonStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        @Override
        public void onMessage(String s) {
            System.out.println("接收到消息: " + s);
            AssistantResult assistantResult = JSON.parseObject(s, AssistantResult.class);
            AssistantResult.HeaderDTO header = assistantResult.getHeader();
            AssistantResult.PayloadDTO payload = assistantResult.getPayload();
            List<AssistantResult.PayloadDTO.ChoicesDTO.TextDTO> text = payload.getChoices().getText();
            if (text != null && text.size() != 0) {
                sb.append(text.get(0).getContent());
            }
        }

        @Override
        public void onClose(int i, String s, boolean b) {
            System.out.println("连接已关闭");
            try {
                synchronized (thread) {
                    thread.notify();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(Exception e) {
            e.printStackTrace();
        }
    }

}
